<template>
  <div class="login-way">
    <el-form :model="registerForm">
      <el-form-item>
        <el-input v-model="registerForm.phone" placeholder="请输入注册手机号" />
      </el-form-item>
      <el-form-item>
        <el-input type="password" v-model="registerForm.password" placeholder="请输入密码" />
      </el-form-item>
      <el-form-item class="password-item">
        <el-input v-model="registerForm.validCode" placeholder="请输入验证码" style="width: 54%"/>
        <el-button icon="el-icon-mobile-phone" class="el-input" @click="send" style="width: 40%;height: 48px;margin-left: 6%" type="success" :disabled="disabled=!show" >
          <span v-show="show">获取验证码</span>
          <span v-show="!show" class="count">{{count}} s</span>
        </el-button>
      </el-form-item>
    </el-form>
    <div class="login-btn" @click="handleRegisterClick">
      注册
    </div>
  </div>
</template>
<script>
import { mapMutations } from 'vuex'
import { userRegister } from 'api/user.js'
import { ERR_OK } from 'api/config.js'
import {getCode} from "../../api/user";
const TIME_COUNT = 60;
export default {

  data () {
    return {
      registerForm: {
        phone: '',
        validCode: '',
        password:'',
        argement: false
      },
      show:true,
      count: '',   // 初始化次数
      timer: null,
    }
  },
  methods: {
    // 注册点击事件
    handleRegisterClick () {
      userRegister(this.registerForm).then(res => {
        let { code, data } = res
        if (code !== ERR_OK) {
          this.$message.error('注册失败')
          return false
        }
        // 缓存用户数据
        this.setUserInfo(data)
        // 关闭弹窗
        this.setShowLogin(false)
        // 重载页面
        window.location.reload()        
      })
    },
    send(){

      getCode(this.registerForm.phone)


      if (!this.timer) {
        this.count = TIME_COUNT;
        this.show = false;
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--;
          } else {
            this.show = true;
            clearInterval(this.timer);  // 清除定时器
            this.timer = null;
          }
        }, 1000)
      }
    },
    // vuex
    ...mapMutations('login', {
      'setUserInfo': 'SET_USER_INFO',
      'setShowLogin': 'SET_SHOW_LOGIN'
    })
  }
}
</script>
<style lang="stylus" scoped>
  @import '~assets/stylus/login-form.styl';

  .login-way
    .agreement
      color: #37f;
      cursor: pointer;
    >>> .el-checkbox__label
      color: #9199a1!important;
</style>
